package com.service;

import com.entity.Details;
import com.entity.ShopGoods;
import com.entity.ShopOrder;
import com.mapper.DetailsMapper;
import com.mapper.ShopOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service("shopOrderService")
public class ShopOrderServiceImp implements ShopOrderService {

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private DetailsMapper detailsMapper;

    @Override
    public List<ShopOrder> findAllOrder() {
        return shopOrderMapper.selectAllOrder();
    }

    @Override
    public void calculateProducts(List<ShopGoods> buyList, ShopOrder order) {
        if(buyList!=null&&buyList.size()>0){
            String UUID =getUUID();
            order.setSerialNumber(UUID);

            float sumMoney = 0f;

            ArrayList<Details> detailsArrayList = new ArrayList<>();
            for (ShopGoods goods : buyList) {
                Details details = new Details();
                if(null!=goods){
                    details.setGoodsID(goods.getId());
                    details.setQuantity(goods.getNumber());

                    //小计
                    float subTotal =goods.getNumber()*goods.getPrice();
                    sumMoney+=subTotal;
                    details.setSerialNumber(UUID);
                    detailsArrayList.add(details);
                }
            }
            order.setCost(sumMoney);
            addOrderAndDetails(order,detailsArrayList);
        }
    }

    @Override
    public void addOrderAndDetails(ShopOrder order, List<Details> detailsList) {
        shopOrderMapper.insertSelective(order);
        if (null != detailsList && detailsList.size() > 0) {
            for (Details details : detailsList) {
                detailsMapper.insert(details);
            }
        }
    }
    public String getUUID(){
        String uuid= UUID.randomUUID().toString().replace("-","");
        return uuid;
    }
}
